package com.common.util;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Task {

    public static int count;

    public static void main(String[] args) {
        //为了保证定时任务的可靠性，应该使用数据库来保证
        Task task = new Task();
        int i = 1000;
        for (int z = 0; z < 100000; z++) {
            task.schedule("sfjkjkd" + i, i = i + 2000);
        }
    }

    public static void schedule(String json, long milliseconds) {
        count++;
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        try {
            Runnable runnable = new Runnable() {
                public void run() {
                    Task task = new Task();
                    task.execute(json);
                    count--;
                    System.out.println("任务开始,当前任务数量" + count);
                }
            };
            //第一个参数是运行对象,第二个参数为执行的延时时间，第三个参数是时间的单位
            service.schedule(runnable, milliseconds, TimeUnit.MILLISECONDS);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            service.shutdown();
        }
    }

    public void execute(String json) {
        //这里可以用写代码的方式，还可以调用http的方式执行任务
        System.out.println("Hello !!" + json);
    }

}  